﻿using System;
using System.Web;
using SyCODE.Component;
using SyCODE.Component.DataFactory;
using System.Data.Common;
using System.Collections.Specialized;
using SyCODE.Component.Cryptography;
using SyCODE.Component.Security;

namespace SyCODE.Blog
{
    /// <summary>
    /// CheckAnswer.aspx 的处理程序
    ///   检测用户输入的问题答案是否正确
    /// </summary>
    public class CheckAnswer : IHttpHandler
    {
        public bool IsReusable
        {
            get
            {
                return true;
            }
        }
        public void ProcessRequest(HttpContext context)
        {
            NameValueCollection nvc = new NameValueCollection(context.Request.Form);
            string crcode = nvc["crcode"];
            //检测验证码
            if (crcode != null && context.Request.Cookies["gpwd"] != null && MD5.Encrypt(crcode.ToUpper()) == context.Request.Cookies["gpwd"].Value)
            {
                nvc.Set("answer", SHA1.Encrypt(nvc["answer"]));

                DBAM dbam = new DBAM();
                dbam.BuildParameters("checkanswer", nvc);

                try
                {
                    DbDataReader dr = dbam.ExecuteReader();

                    if (dr.Read())
                    {
                        if (dr.GetInt32(0) > 0)
                        {
                            //当问题答案正确时发送临时授权，浏览器未关闭时有效
                            Ticket ticket = new Ticket(nvc["account"], nvc["answer"]);
                            ticket.Expires = DateTime.Now.AddMinutes(20);
                            ticket.Issue("answer");

                            context.Response.Write("1");
                        }
                        else
                        {
                            context.Response.Write("0");
                        }
                    }

                    dr.Close();
                }
                finally
                {
                    dbam.Dispose();
                }
            }
        }
    }
}
